package com.cheys.webapp.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author kucs 生成验证码类
 *
 */
public class PassCode {
	public static final char[] code = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 
			'j', 'k', 'l', 'm', 'n','o','p','q','r','s','t','u','v','w','x','y','z',
			'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H',
			'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
	public void createPasscode(HttpServletResponse response,HttpServletRequest request) throws IOException{
		int width = 80;
		int height = 32;
		BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();
		//创建一个随机数生成器
		Random random = new Random();
		
		//设定图像背景色
		g.setColor(getRandColor(200,250));
		g.fillRect(0, 0, width, height);
		//创建字体
		Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 29);
		//设置字体
		g.setFont(font);
		//画边框
		g.setColor(Color.white);
		g.drawRect(0, 0, width, height);
		g.setColor(getRandColor(160, 200));
		//随机产生50条干扰线，使图像中的认证码不易被其他程序探测到
		for(int i=0;i<50;i++){
			int x = random.nextInt(width); 
			int y = random.nextInt(height); 
			int xl = random.nextInt(12); 
			int yl = random.nextInt(12); 
			g.drawLine(x, y, xl, yl);
		}
		//生成随机思维验证码
		int length = 4;
		StringBuffer randomcode  = new StringBuffer();
		for(int i = 0;i<length;i++){
			int index = random.nextInt(code.length - 1);
			String strRand = String.valueOf(code[index]);
			g.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110),20 + random.nextInt(110)));
			g.drawString(strRand, 15 * i + 6, 24);
			
			randomcode.append(strRand);
		}
		request.getSession().setAttribute("randomcode", randomcode.toString());
		//图像失效
		g.dispose();
		//禁止图像缓存
		response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.flush();
         sos.close();
	}
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if(fc > 255){
			fc = 255;
		}
		if(bc > 255){
			bc = 255;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc -fc);
		int b = fc + random.nextInt(bc -fc);
		return new Color(r, g, b);
	}
}
